import {
  getExtensionRootPath,
  loadJsxFile,
  methodEvaler,
} from '../../core/common'
import { join } from 'path'

import {
  renderProject,
  TaskType,
  TaskInfo,
  Task,
  taskMap,
  renderXML,
  renderFile,
} from './task'

import { HostType } from '../../constants/common'

const _evalMethod = methodEvaler(HostType.ame)

export type { TaskType, TaskInfo, Task } from './task'
/**
 * 添加合成任务
 *
 * @export
 * @param {TaskType} type
 * @param {TaskInfo} { source, format, preset, sequenceId, destination }
 * @return {*}  {Promise<Task>}
 */
export async function addTask(
  type: TaskType,
  { source, format, preset, sequenceId, destination }: TaskInfo
): Promise<Task> {
  switch (type) {
    case TaskType.PROJECT:
      if (source && format && preset && sequenceId && destination) {
        return await renderProject(
          source,
          format,
          preset,
          sequenceId,
          destination
        )
      } else {
        throw new Error('参数不全')
      }
    case TaskType.XML:
      if (source && format && preset && destination) {
        return await renderXML(source, format, preset, destination)
      } else {
        throw new Error('参数不全')
      }
    case TaskType.FILE:
      if (source && format && preset && destination) {
        return await renderFile(source, format, preset, destination)
      } else {
        throw new Error('参数不全')
      }
    default:
      throw new Error('Unknown Task Type')
  }
  // 检查参数是否合法
  // 做前置处理 比如创建文件夹 检查文件是否存在
  // 添加任务 调用不通的jsx
}

/**
 * 开始合成
 *
 * @export
 * @return
 */
export function startBatch() {
  return _evalMethod('runBatch')
}

/**
 * 停止合成
 *
 * @export
 * @return
 */
export function stopBatch() {
  return _evalMethod('stopBatch')
}

/**
 * 暂停合成
 *
 * @export
 * @return
 */
export function pasueBatch() {
  return _evalMethod('pasueBatch')
}

/**
 * 获取任务信息
 *
 * @export
 * @param id
 * @return Task
 */
export function getTaskInfo(id: number) {
  return taskMap.get(id)
}

/**
 * 初始化, 所有ame下api需要在初始化后使用
 *
 * @export
 */
export async function init() {
  const jsxPath = join(getExtensionRootPath(), './jsx/ame')
  console.log('init jsx', jsxPath)
  await loadJsxFile(jsxPath)
  return _evalMethod('ping') // 检查是否初始化成功
}
